package com.xuluoji.urldecoder;

import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;


public class MainActivity extends AppCompatActivity {
    Context context = null;

    EditText view_txt_input = null;
    TextView view_txt_output = null;

    ClipboardManager cm = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        context = getApplicationContext();
        cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);

        view_txt_input = (EditText) findViewById(R.id.et_input);
        view_txt_output = (TextView) findViewById(R.id.tv_output);

        Button bt = (Button) findViewById(R.id.bt_paste);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                eventPaste();

            }
        });

        bt = (Button) findViewById(R.id.bt_encode);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                eventEncode();

            }
        });

        bt = (Button) findViewById(R.id.bt_decode);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                eventDecode();

            }
        });

        bt = (Button) findViewById(R.id.bt_copy);
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                eventCopy();

            }
        });

        Log.i("MainActivity", "Hello World!");

        schemeParse(getIntent());
    }

    private void eventPaste() {
        System.out.println("粘贴 SDK_INT：" + android.os.Build.VERSION.SDK_INT);
        Toast.makeText(context, "粘贴 SDK_INT：" + android.os.Build.VERSION.SDK_INT,
                Toast.LENGTH_SHORT).show();

        // 粘贴
        if (android.os.Build.VERSION.SDK_INT > 11) {
            if (!cm.hasPrimaryClip()) {
                return;
            } else if (!cm.getPrimaryClipDescription()
                    .hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
                return;
            }
            ClipData.Item it = cm.getPrimaryClip().getItemAt(0);
            view_txt_input.setText(it.coerceToText(context));
        } else {
            view_txt_input.setText(cm.getText());
        }
    }

    private void eventEncode() {
        CharSequence val = view_txt_input.getText();
        System.out.println("URL编码：" + val.toString());
        Toast.makeText(context, "URL编码", Toast.LENGTH_SHORT).show();

        // 编码
        String url = "";
        try {
            url = URLEncoder.encode(val.toString(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        view_txt_output.setText(url);
    }

    private void eventDecode() {
        CharSequence val = view_txt_input.getText();
        System.out.println("URL解码：" + val.toString());
        Toast.makeText(context, "URL解码", Toast.LENGTH_SHORT).show();

        // 解码
        String url = "";
        try {
            url = URLDecoder.decode(val.toString(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        view_txt_output.setText(url);
    }

    private void eventCopy() {
        System.out.println("复制 SDK_INT：" + android.os.Build.VERSION.SDK_INT);
        Toast.makeText(context, "复制 SDK_INT：" + android.os.Build.VERSION.SDK_INT,
                Toast.LENGTH_SHORT).show();

        // 复制
        if (android.os.Build.VERSION.SDK_INT > 11) {
            cm.setPrimaryClip(ClipData.newPlainText("URL", view_txt_output.getText()));
        } else {
            cm.setText(view_txt_output.getText());
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        schemeParse(intent);
    }

    private void schemeParse(Intent intent) {
        Uri uri = intent.getData();
        if (uri == null) {
            return;
        }

        System.out.println("scheme传入：" + uri.toString());
        // 获得URI末尾段
        view_txt_input.setText(uri.getLastPathSegment());
        view_txt_output.setText(uri.getLastPathSegment());

        eventCopy();

        startupGW();
    }

    private boolean startupGW() {
        // jp.gamewith.monst
        Intent it = getPackageManager()
                .getLaunchIntentForPackage("jp.gamewith.monst");

        // jp.gamewith.gamewith
        if (it == null) {
            it = getPackageManager()
                    .getLaunchIntentForPackage("jp.gamewith.gamewith");
        }

        if (it != null) {
            Toast.makeText(context, "URL已复制, GW启动", Toast.LENGTH_SHORT).show();
            startActivity(it);
            return true;
        }

        // Toast.makeText(context, "未安装GW", Toast.LENGTH_SHORT).show();
        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 点击系统返回按钮，不退出APP，改为返回桌面
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_about, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.id_menu_about:
                // 打开链接
                try {
                    Intent it = new Intent(Intent.ACTION_VIEW);
                    it.setData(Uri.parse("https://gitee.com/xuluoji/urldecoder"));
                    startActivity(it);
                } catch (Exception e) {
                        Toast.makeText(context, "未发现浏览器", Toast.LENGTH_SHORT).show();
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

}
